/**
 * The search view.
 *
 * (c) Copyright 2011 Nokia Corporation. All rights reserved.
 */

import QtQuick 1.1
import com.nokia.symbian 1.1

import "../script/ajax.js" as AjaxScript
import "../script/common.js" as CommonScript

Page {
    id: searchView;

    anchors {
        fill: parent;
        leftMargin: 10;
        rightMargin: 10;
    }

    tools: toolBarLayout;

    Component.onCompleted: {
        fetchTags();
    }

    // Top bar
    TopBar {
        id: searchTopBar;
        width: parent.width;
        height: 70;
        titleImage: "qrc:/gfx/title_search.png";
    }

    // Free text search
    Row {
        id: freeTextArea;
        spacing: 10;
        anchors.top: searchTopBar.bottom;
        anchors.topMargin: 5;

        TextField {
            id: freeText;

            width: searchView.width * 0.5;
            text: CommonScript.FREE_TEXT;
        }

        Button {
            id: btnSearch;
            text: "Search";

            onClicked: {
                if (!searchView.pageStack.busy) {
                    searchBetas();
                }
            }
        }
    }

    // Toggle categories button
    Button {
        id: btnToggleCategories;
        anchors.top: freeTextArea.bottom;
        anchors.topMargin: 10;
        text: "Unselect all categories";

        onClicked: {
            toggleCheckBoxes();
        }
    }

    Text {
        id: errorTextSearchView;
        width: parent.width;
        anchors.top: btnToggleCategories.bottom;
        anchors.topMargin: 10;
        text: "Unable to fetch tags. Ensure that your device is connected to the Internet.";
        opacity: 0;
        wrapMode: "WordWrap";
    }

    ScrollDecorator {
        flickableItem: categoryView;
    }

    // Category view
    ListView {
        id: categoryView;
        width: parent.width;
        anchors.top: btnToggleCategories.bottom;
        anchors.bottom: parent.bottom;
        anchors.topMargin: 10;
        model: categoryModel;
        delegate: categoryItem;
        clip: true;
    }

    ListModel {
        id: categoryModel;
    }

    Component {
        id: categoryItem;

        Item {
            width: parent.width;
            height: cb.height;

            Row {
                spacing: 10;

                CheckBox {
                    id: cb;
                    checked: cbChecked;
                    onClicked: {
                        checkBoxClicked(index);
                    }
                }

                Text {
                    text: category;
                }
            }

            MouseArea {
                anchors.fill: parent;
                onClicked: {
                    checkBoxClicked(index);
                }
            }
        }
    }

    // Workaround for bug QTCOMPONENTS-1178
    // (https://bugreports.qt.nokia.com/browse/QTCOMPONENTS-1178). Forces the
    // highlight to search button. When the bug is fixed, this function is no
    // longer needed.
    function updateToolBarHighlight() {
        tabControls.checkedButton = searchTabButton;
    }

    // Called when a checkbox is clicked.
    function checkBoxClicked(index) {
        var currentItem = categoryModel.get(index);
        currentItem.cbChecked = !currentItem.cbChecked;

        // If all checkboxes have been checked, change the toggle button to
        // "Unselect all categories"
        var checkboxesChecked = 0;
        for (var i = 0; i < categoryModel.count; i++) {
            var item = categoryModel.get(i);
            if (item.cbChecked) {
                checkboxesChecked++;
            }
        }
        if (checkboxesChecked == categoryModel.count) {
            btnToggleCategories.text = "Unselect all categories";
        } else {
            btnToggleCategories.text = "Select all categories";
        }
    }

    // Checks or unchecks all checkboxes based on the current state of the
    // toggle button.
    function toggleCheckBoxes() {
        if (btnToggleCategories.text == "Unselect all categories") {
            for (var i = 0; i < categoryModel.count; i++) {
                var item = categoryModel.get(i);
                item.cbChecked = false;
            }
            btnToggleCategories.text = "Select all categories";
        } else {
            for (var i = 0; i < categoryModel.count; i++) {
                var item = categoryModel.get(i);
                item.cbChecked = true;
            }
            btnToggleCategories.text = "Unselect all categories";
        }
    }

    // Fetches the tags (categories) from the server.
    function fetchTags() {
        var req = AjaxScript.createXMLHttpRequest();
        if (req) {
            var url = CommonScript.BETA_LABS_API_URL + "/tags";
            AjaxScript.loadXMLDoc(req, url, cbFetchTags);
        }
    }

    // Called when the server responds to the fetch tags call.
    function cbFetchTags(xml, text) {
        busyIndicator.opacity = 0;
        busyIndicator.running = false;

        if (xml === null) {
            errorTextSearchView.opacity = 1;
            return;
        }

        errorTextSearchView.opacity = 0;

        var groups =
            CommonScript.getElementsByTagName(xml.documentElement, "group");
        var categories = CommonScript.getElementsByTagName(groups[1], "tag");
        for (var i = 0; i < categories.length; i++) {
            var category = categories[i].firstChild.nodeValue;
            categoryModel.append({"category": category, "cbChecked": true});
        }
    }

    // Searches betas based either on the search phrase or on the search
    // parameters.
    function searchBetas() {
        var resultsPage = searchView.pageStack.push(Qt.resolvedUrl("ResultsView.qml"));

        var freeTextPhrase = freeText.text;
        if (freeTextPhrase.length !== 0 &&
                freeTextPhrase != CommonScript.FREE_TEXT) {
            // Perform a free text search based on the search phrase written
            // in the text input.
            resultsPage.resultsBetaView.getBasedOnFreeText(freeTextPhrase);
        } else {
            // Perform a search based on the parameters specified.
            var searchTags = createSearchTags();
            resultsPage.resultsBetaView.getBasedOnTags(searchTags);
        }
    }

    // Creates a string of tags that can be used to search beta applications.
    function createSearchTags() {
        var strTags = "";
        var strCategory = "";
        // Iterate through the checkboxes.
        for (var i = 0; i < categoryModel.count; i++) {
            var item = categoryModel.get(i);
            if (item.cbChecked) {
                // Remove commas from the categories, because they cause
                // incorrect search results with QtWebKit. Note, however,
                // that removing commas may render some categories useless.
                strCategory += item.category.replace(",", "") + ",";
            }
        }

        if (strCategory.length > 0) {
            strTags += strCategory;
        }

        var strPlatforms = "";
        for (var i = 0; i < CommonScript.SUPPORTED_PLATFORMS.length; i++) {
            strPlatforms += CommonScript.SUPPORTED_PLATFORMS[i] + ",";
        }

        if (strPlatforms.length > 0) {
            // Delete the last comma
            strPlatforms = strPlatforms.substring(0, strPlatforms.length - 1);
            strTags += strPlatforms;
        }
        return strTags;
    }
}
